<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  <!-- 谷歌收录 -->
  <meta name="google-site-verification" content="-5hl8eC4wfapGZhZouwMVUcKG0iaynijVRJbqVlzXm4" />
  
  
  <title>如何将嵌套列表展开为一维 | 鴻塵</title>
  <meta name="description" content="文章说明文章作者：鴻塵参考资料：  How to make a flat list out of a list of lists? Right Foot In: More on python flatten（有缘人才能打开） Flatten an irregular list of lists How Not to Flatten a List of Lists in Python  文章链接：">
<meta property="og:type" content="article">
<meta property="og:title" content="如何将嵌套列表展开为一维">
<meta property="og:url" content="https://hwame.top/20210610/flatten-a-nested-list.html">
<meta property="og:site_name" content="鴻塵">
<meta property="og:description" content="文章说明文章作者：鴻塵参考资料：  How to make a flat list out of a list of lists? Right Foot In: More on python flatten（有缘人才能打开） Flatten an irregular list of lists How Not to Flatten a List of Lists in Python  文章链接：">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-06-10T11:56:05.000Z">
<meta property="article:modified_time" content="2021-06-20T10:43:21.000Z">
<meta property="article:author" content="鴻塵">
<meta property="article:tag" content="python">
<meta name="twitter:card" content="summary">
  <!-- Canonical links -->
  <link rel="canonical" href="https://hwame.top/20210610/flatten-a-nested-list.html">
  
    <link rel="alternate" href="true" title="鴻塵" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/css/style.css">

  
    <link href="//cdn.jsdelivr.net/npm/katex@0.9.0/dist/katex.min.css" rel="stylesheet">
  
  
  
    <link href="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css" rel="stylesheet">
  
  
<meta name="generator" content="Hexo 5.4.2"></head>


<script src="https://cdn.jsdelivr.net/gh/bobcn/hexo_resize_image.js@master/hexo_resize_image.js"></script>
<body class="main-center theme-purple" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="https://hwame.top" target="_blank">
          <img class="img-circle img-rotate" src="https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">鴻塵</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">Pythoner, Data Analyst</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> 湖北-武汉</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="搜索" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav menu-highlight">
        
        
        <li class="menu-item menu-item-home">
          <a href="/.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">首页</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="/archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">归档</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="/categories">
            
            <i class="icon icon-folder-open"></i>
            
            <span class="menu-title">分类</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="/tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">标签</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-repository">
          <a href="/repository">
            
            <i class="icon icon-project"></i>
            
            <span class="menu-title">资源</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-gallery">
          <a href="/gallery">
            
            <i class="icon icon-delicious"></i>
            
            <span class="menu-title">相册</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-links">
          <a href="/links">
            
            <i class="icon icon-friendship"></i>
            
            <span class="menu-title">友链</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-about">
          <a href="/about">
            
            <i class="icon icon-cup-fill"></i>
            
            <span class="menu-title">关于</span>
          </a>
        </li>
        
      </ul>
      
	
    <ul class="social-links">
    	
        <li><a href="https://github.com/hwame" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="https://weibo.com/hwamei" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="https://www.zhihu.com/people/hwame" target="_blank" title="Zhihu" data-toggle=tooltip data-placement=top><i class="icon icon-zhihu"></i></a></li>
        
        <li><a href="https://segmentfault.com/u/hwame" target="_blank" title="Segmentfault" data-toggle=tooltip data-placement=top><i class="icon icon-segmentfault"></i></a></li>
        
        <li><a href="https://gitee.com/hwame" target="_blank" title="Gitee" data-toggle=tooltip data-placement=top><i class="icon icon-gitee"></i></a></li>
        
        <li><a href="/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-stackexchange"></i>公告</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>欢迎来到鴻塵的博客!<br>鴻塵的<u><a target="_blank" rel="noopener" href="https://weibo.com/hwamei" style="color:#E541E5;">微博</a></u>主页，鴻塵的<u><a target="_blank" rel="noopener" href="https://github.com/hwame" style="color:#E541E5;">Github</a></u>主页，如果我可以忘记的<u><a target="_blank" rel="noopener" href="https://www.zhihu.com/people/hwame" style="color:#E541E5;">知乎</a></u>主页。</p>
            </div>
        </div>
    </div>
</div>

    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-tags"></i>标签云</h3>
    <div class="widget-body tagcloud">
      <a href="/tags/CentOS/" style="font-size: 13px; color: #fff">CentOS</a> <a href="/tags/Go/" style="font-size: 13.2px; color: #fff">Go</a> <a href="/tags/Hexo/" style="font-size: 13.8px; color: #fff">Hexo</a> <a href="/tags/Linux/" style="font-size: 14px; color: #fff">Linux</a> <a href="/tags/Linux%E9%83%A8%E7%BD%B2/" style="font-size: 13px; color: #fff">Linux部署</a> <a href="/tags/MongoDB/" style="font-size: 13.4px; color: #fff">MongoDB</a> <a href="/tags/Spark/" style="font-size: 13px; color: #fff">Spark</a> <a href="/tags/matplotlib/" style="font-size: 13.2px; color: #fff">matplotlib</a> <a href="/tags/miscellanea/" style="font-size: 13.6px; color: #fff">miscellanea</a> <a href="/tags/python/" style="font-size: 14px; color: #fff">python</a> <a href="/tags/shell/" style="font-size: 13.6px; color: #fff">shell</a> <a href="/tags/%E5%A4%A7%E6%95%B0%E6%8D%AE/" style="font-size: 13px; color: #fff">大数据</a> <a href="/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" style="font-size: 13px; color: #fff">数据结构与算法</a> <a href="/tags/%E7%88%AC%E8%99%AB/" style="font-size: 13px; color: #fff">爬虫</a>
    </div>
  </div>

<script type="text/javascript">
    var everytag=document.getElementsByClassName("widget-body tagcloud")[0].children;
    for (var i = everytag.length - 1; i >= 0; i--) {
    	var r=Math.floor(Math.random()*255);
        var g=Math.floor(Math.random()*255);
        var b=Math.floor(Math.random()*255);
        everytag[i].style.background = "rgb("+r+","+g+","+b+")";
    }
</script>
    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-folder-open"></i>分类</h3>
    <div class="widget-body">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Go/">Go</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Hexo/">Hexo</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Linux/">Linux</a><span class="category-list-count">8</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/MongoDB/">MongoDB</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/miscellanea/">miscellanea</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/python/">python</a><span class="category-list-count">7</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/">数据结构与算法</a><span class="category-list-count">1</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-archives-fill"></i>归档</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2022/">2022</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/">2021</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/">2020</a><span class="archive-list-count">17</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-shu-fill"></i>最新文章</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled ">
        
          <li>
            
            <div class="item-thumb">
              <a href="/20220327/channel-and-goroutine-in-go.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/icon-golang.jpeg)" alt="Go语言中的通道" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Go/">Go</a>
              </p>
              <p class="item-title">
                <a href="/20220327/channel-and-goroutine-in-go.html" class="title">Go语言中的通道</a>
              </p>
              <p class="item-date">
                <time datetime="2022-03-27T11:06:16.000Z" itemprop="datePublished">2022-03-27</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220323/when-to-use-pointer-in-go.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/icon-golang.jpeg)" alt="Go语言什么时候使用指针" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Go/">Go</a>
              </p>
              <p class="item-title">
                <a href="/20220323/when-to-use-pointer-in-go.html" class="title">Go语言什么时候使用指针</a>
              </p>
              <p class="item-date">
                <time datetime="2022-03-23T12:49:57.000Z" itemprop="datePublished">2022-03-23</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220228/awesome-images-in-markdown.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg)" alt="Markdown中图片的高级用法" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/miscellanea/">miscellanea</a>
              </p>
              <p class="item-title">
                <a href="/20220228/awesome-images-in-markdown.html" class="title">Markdown中图片的高级用法</a>
              </p>
              <p class="item-date">
                <time datetime="2022-02-28T15:27:50.000Z" itemprop="datePublished">2022-02-28</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220116/shell-regular-expression.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/linux-icon.png)" alt="Shell正则表达式" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Linux/">Linux</a>
              </p>
              <p class="item-title">
                <a href="/20220116/shell-regular-expression.html" class="title">Shell正则表达式</a>
              </p>
              <p class="item-date">
                <time datetime="2022-01-16T14:13:05.000Z" itemprop="datePublished">2022-01-16</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20211009/install-linux-on-android-phone.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg)" alt="如何在安卓手机上安装Linux发行版" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/miscellanea/">miscellanea</a>
              </p>
              <p class="item-title">
                <a href="/20211009/install-linux-on-android-phone.html" class="title">如何在安卓手机上安装Linux发行版</a>
              </p>
              <p class="item-date">
                <time datetime="2021-10-09T15:16:37.000Z" itemprop="datePublished">2021-10-09</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <nav id="toc" class="article-toc">
      <h3 class="toc-title">文章目录</h3>
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E5%BC%95%E8%A8%80"><span class="toc-number">1.</span> <span class="toc-text">1.引言</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88"><span class="toc-number">2.</span> <span class="toc-text">2.解决方案</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-%E6%96%B9%E6%B3%95%E4%B8%80%EF%BC%9Afunctools-reduce"><span class="toc-number">2.1.</span> <span class="toc-text">2.1.方法一：functools.reduce</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-%E6%96%B9%E6%B3%95%E4%BA%8C%EF%BC%9A%E5%88%97%E8%A1%A8%E7%94%9F%E6%88%90%E5%BC%8F"><span class="toc-number">2.2.</span> <span class="toc-text">2.2.方法二：列表生成式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-%E6%96%B9%E6%B3%95%E4%B8%89%EF%BC%9Aitertools-chain"><span class="toc-number">2.3.</span> <span class="toc-text">2.3.方法三：itertools.chain</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4-%E6%96%B9%E6%B3%95%E5%9B%9B%EF%BC%9Asum"><span class="toc-number">2.4.</span> <span class="toc-text">2.4.方法四：sum</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-5-%E6%96%B9%E6%B3%95%E4%BA%94%EF%BC%9A%E7%8E%B0%E6%9C%89%E7%9A%84%E8%BD%AE%E5%AD%90"><span class="toc-number">2.5.</span> <span class="toc-text">2.5.方法五：现有的轮子</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-6-%E6%96%B9%E6%B3%95%E5%85%AD%EF%BC%9Aoperator"><span class="toc-number">2.6.</span> <span class="toc-text">2.6.方法六：operator</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-6-%E6%96%B9%E6%B3%95%E4%B8%83%EF%BC%9Amap"><span class="toc-number">2.7.</span> <span class="toc-text">2.6.方法七：map</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E5%85%B6%E4%BB%96%E9%97%AE%E9%A2%98"><span class="toc-number">3.</span> <span class="toc-text">3.其他问题</span></a></li></ol>
    </nav>
  </div>
</aside>

<main class="main" role="main">
  <div class="content">
  <article id="post-flatten-a-nested-list" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      如何将嵌套列表展开为一维
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar"></i>
	<a href="/20210610/flatten-a-nested-list.html" class="article-date">
	  发布于 <time datetime="2021-06-10T11:56:05.000Z" itemprop="datePublished">2021-06-10</time>
	</a>
</span>
<span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/20210610/flatten-a-nested-list.html" class="article-date">
	  更新于 <time datetime="2021-06-20T10:43:21.000Z" itemprop="dateUpdated">2021-06-20</time>
	</a>
</span>
        
  <span class="article-category">
    <i class="icon icon-folder"></i>
    <a class="article-category-link" href="/categories/python/">python</a>
  </span>

        
  <span class="article-tag">
    <i class="icon icon-tags"></i>
	<a class="article-tag-link-link" href="/tags/python/" rel="tag">python</a>
  </span>


        

	<span class="article-read hidden-xs">
    	<i class="icon icon-eye-fill" aria-hidden="true"></i>
    	<span id="/20210610/flatten-a-nested-list.html" class="leancloud_visitors"  data-flag-title="如何将嵌套列表展开为一维">
			<span class="leancloud-visitors-count">0</span>
		</span>
    </span>

        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/20210610/flatten-a-nested-list.html#comments" class="article-comment-link">评论</a></span>
        
	
		<span class="post-wordcount hidden-xs" itemprop="wordCount">字数统计: 2k(字)</span>
	
	
		<span class="post-readcount hidden-xs" itemprop="timeRequired">阅读时长: 8(分)</span>
	

      </div>
      <div style="background-color:#D7BDE2;border:1px solid #D7BDE2;border-radius:10px;padding:5px">
          <b>温馨提示</b>：点击页面下方<i style="color:red" class="icon icon-anchor"></i>以展开或折叠目录
      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <blockquote>
<p><font size=5><b>文章说明</b></font><br><strong>文章作者：</strong><a href="https://hwame.top">鴻塵</a><br><strong>参考资料：</strong></p>
<ul>
<li><a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists">How to make a flat list out of a list of lists?</a></li>
<li><a target="_blank" rel="noopener" href="http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html">Right Foot In: More on python flatten</a>（有缘人才能打开）</li>
<li><a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists">Flatten an irregular list of lists</a></li>
<li><a target="_blank" rel="noopener" href="https://mathieularose.com/how-not-to-flatten-a-list-of-lists-in-python">How Not to Flatten a List of Lists in Python</a></li>
</ul>
<p><strong>文章链接：</strong><a href="https://hwame.top/20210610/flatten-a-nested-list.html">https://hwame.top/20210610/flatten-a-nested-list.html</a></p>
</blockquote>
<h2 id="1-引言"><a href="#1-引言" class="headerlink" title="1.引言"></a>1.引言</h2><p>闲来无事逛<a target="_blank" rel="noopener" href="https://stackoverflow.com">Stack Overflow</a>，发现了一个挺有意思的问题：<a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists">How to make a flat list out of a list of lists?</a>。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 怎样快速优雅地将src转换成dst？</span></span><br><span class="line">src = [[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>], [<span class="number">7</span>], [<span class="number">8</span>, <span class="number">9</span>]]</span><br><span class="line">dst = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>]</span><br></pre></td></tr></table></figure>
<p>乍一看，对于所给的二维数组，<code>for</code>循环是最容易想到的思路，但是有没有<font color=purple><b>some cool “one-liner”</b></font>的办法呢？顺着这个问题往下看，还挺有意思。</p>
<p><strong>说明：</strong>此处仅讨论各方法的正确性，至于性能和效率可自行测试。</p>
<h2 id="2-解决方案"><a href="#2-解决方案" class="headerlink" title="2.解决方案"></a>2.解决方案</h2><h3 id="2-1-方法一：functools-reduce"><a href="#2-1-方法一：functools-reduce" class="headerlink" title="2.1.方法一：functools.reduce"></a>2.1.方法一：<code>functools.reduce</code></h3><p>该问题的提出者<a target="_blank" rel="noopener" href="https://stackoverflow.com/users/110527/emma">Emma</a>提供了一个思路，利用标准库函数<code>reduce</code>：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> reduce</span><br><span class="line">src = [[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>], [<span class="number">7</span>], [<span class="number">8</span>, <span class="number">9</span>]]</span><br><span class="line"><span class="comment">#reduce(lambda x, y: x.extend(y), src)</span></span><br><span class="line">reduce(<span class="keyword">lambda</span> x, y: x + y, src)</span><br></pre></td></tr></table></figure><br>这个方法是可行的，但为何不能用<code>x.extend(y)</code>呢？原因是列表的<code>extend</code>方法不返回值（返回<code>None</code>），故在下一轮次的reduce过程中会导致<code>None.extend</code>，从而<code>raise AttributeError: &#39;NoneType&#39; object has no attribute &#39;extend&#39;</code>。而<strong>列表</strong>加法则会返回「extended」列表。</p>
<p>如果非要用<code>extend</code>呢？既然返回<code>None</code>，我们是否可以人为给返回赋值？<a target="_blank" rel="noopener" href="https://stackoverflow.com/users/437728/lbarret">LBarret</a>给出了一个方案：<code>reduce(lambda x, y : x.extend(y) or x, src, [])</code>，或者省略<code>initial</code>参数：<code>reduce(lambda x, y : x.extend(y) or x, src)</code>。其中<code>x.extend(y) or x</code>实现了<code>x + y</code>并返回<code>x</code>，因为<code>bool(x.extend(y)) = False</code>。</p>
<p><a target="_blank" rel="noopener" href="https://stackoverflow.com/users/893/greg-hewgill">Greg Hewgill</a>提到，<code>extend()</code>方法会修改列表<code>x</code>，而不是返回一个<code>functools.reduce()</code>所期望的「有用的」值，因此<code>x + y</code>优于<code>x.extend(y)</code>。</p>
<p>需要指出的是，这种<code>reduce</code>方法只能解决二维数组，多层嵌套或非列表元素将抛错，例如：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">src1 = [[<span class="number">1</span>], [], [<span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>], <span class="number">5</span>]           <span class="comment"># 含有非列表元素5</span></span><br><span class="line">src2 = [[<span class="number">1</span>], [], [<span class="number">2</span>, <span class="number">3</span>], [[<span class="number">4</span>], [<span class="number">5</span>, <span class="number">6</span>]]]  <span class="comment"># 多层嵌套</span></span><br><span class="line">reduce(<span class="keyword">lambda</span> x, y: x + y, src1)</span><br><span class="line"><span class="comment"># TypeError: can only concatenate list (not &quot;int&quot;) to list</span></span><br><span class="line"></span><br><span class="line">reduce(<span class="keyword">lambda</span> x, y: x + y, src2)</span><br><span class="line"><span class="comment"># [1, 2, 3, [4], [5, 6]]</span></span><br><span class="line"><span class="comment"># 只能展开一层，若再reduce一次则含非列表元素</span></span><br></pre></td></tr></table></figure></p>
<h3 id="2-2-方法二：列表生成式"><a href="#2-2-方法二：列表生成式" class="headerlink" title="2.2.方法二：列表生成式"></a>2.2.方法二：列表生成式</h3><p>列表生成式也是很容易想到的办法，因为它本质上就是<code>for</code>循环：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 列表生成式</span></span><br><span class="line">dst = [item <span class="keyword">for</span> sublist <span class="keyword">in</span> src <span class="keyword">for</span> item <span class="keyword">in</span> sublist]</span><br><span class="line"></span><br><span class="line"><span class="comment"># for循环等价写法</span></span><br><span class="line">dst = []</span><br><span class="line"><span class="keyword">for</span> sublist <span class="keyword">in</span> src:</span><br><span class="line">    <span class="keyword">for</span> item <span class="keyword">in</span> sublist:</span><br><span class="line">        dst.append(item)</span><br><span class="line"></span><br><span class="line"><span class="comment"># lambda表达式</span></span><br><span class="line">flatten = <span class="keyword">lambda</span> t: [item <span class="keyword">for</span> sublist <span class="keyword">in</span> t <span class="keyword">for</span> item <span class="keyword">in</span> sublist]</span><br><span class="line">dst = flatten(src)</span><br></pre></td></tr></table></figure><br>两层<code>for</code>循环写成列表生成式不太直观，借用<a target="_blank" rel="noopener" href="https://stackoverflow.com/users/75033/john-mee">John Mee</a>的例子会更容易理解和应用：<code>[leaf for tree in forest for leaf in tree]</code>。表达式中「叶 → 树 → 林」的关系很清晰地表现了内外循环的层级。</p>
<p>当然也有不同的观点，例如<a target="_blank" rel="noopener" href="https://stackoverflow.com/users/6419007/eric-duminil">Eric Duminil</a>和<a target="_blank" rel="noopener" href="https://stackoverflow.com/users/1335793/davos">Davos</a>。尽管John Mee的写法与<code>for</code>循环相同，但顺序杂乱不易理解（直观仅限于<code>leaf</code>、<code>tree</code>和<code>forest</code>），Davos更推荐使用<code>leaf for leaf in tree for tree in forest</code>这种「递进式写法」。</p>
<h3 id="2-3-方法三：itertools-chain"><a href="#2-3-方法三：itertools-chain" class="headerlink" title="2.3.方法三：itertools.chain"></a>2.3.方法三：<code>itertools.chain</code></h3><p><code>itertools.chain</code>先将二维数组解包为一维然后连接为迭代器，再转化为列表；<code>itertools.chain.from_iterable</code>则无需先解包：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> itertools</span><br><span class="line">src = [[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>], [<span class="number">7</span>], [<span class="number">8</span>, <span class="number">9</span>]]</span><br><span class="line"></span><br><span class="line">dst = <span class="built_in">list</span>(itertools.chain(*src))</span><br><span class="line">dst = <span class="built_in">list</span>(itertools.chain.from_iterable(src))</span><br></pre></td></tr></table></figure><br>借用该回答下<a target="_blank" rel="noopener" href="https://stackoverflow.com/users/1342079/tim-dierks">Tim Dierks</a>的评论，<code>*</code>将列表解包为多个参数传递给<code>chain</code>，导致将顶级列表（最外层）扩展为参数，再将这些可迭代对象连接在一起而不会进入更深层级。在这种情况下，列表生成式将比链式用法的可读性更好。</p>
<h3 id="2-4-方法四：sum"><a href="#2-4-方法四：sum" class="headerlink" title="2.4.方法四：sum"></a>2.4.方法四：<code>sum</code></h3><p>这种方法既不直观也不高效，但是很有趣，计算机科学中的monoids定义如下：</p>
<blockquote>
<p><strong><a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Monoid#Monoids_in_computer_science">Monoids in computer science</a></strong>【来自维基百科】</p>
<p>在计算机科学中，许多<a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Abstract_data_types">抽象数据类型（Abstract Data Types，ADT）</a>都具有monoid结构。在一个常见的模式中，monoid的一<a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Sequence">系列</a>元素被「<a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Fold_(higher-order_function"><strong>折叠</strong></a>)」或「<strong>累积</strong>」以产生最终值。例如，许多迭代算法需要在每次迭代时更新某种「运行总数」；这种模式可以通过monoid运算优雅地表达。或者，monoid运算的关联性确保可以通过使用<a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Prefix_sum">前缀和</a>或类似算法来<a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Parallelization">并行化</a>运算，以便有效地利用多个内核或处理器。<br>给定一系列「$M$类型」且具有「标识元素$\varepsilon$」和「关联操作$\bullet$」的值，折叠操作定义如下：</p>
<script type="math/tex; mode=display">\displaystyle \mathrm {fold:} M^{*}\rightarrow M=\ell \mapsto {\begin{cases}\varepsilon &{\mbox{if }}\ell =\mathrm {nil} \\m\bullet \mathrm {fold}\,\ell '&{\mbox{if }}\ell =\mathrm {cons} \,m\,\ell '\end{cases}}</script><p>此外，如果给定其元素的序列化，任何<a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Data_structure">数据结构</a>都可以以类似的方式「折叠」。例如，「折叠」<a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Binary_tree">二叉树</a>的结果可能会因<a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Tree_traversal">遍历方式</a>（前序遍历pre-order与后序遍历post-order）的不同而不同。</p>
</blockquote>
<p>代码如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">src = [[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>], [<span class="number">7</span>], [<span class="number">8</span>, <span class="number">9</span>]]</span><br><span class="line">dst = <span class="built_in">sum</span>(src, [])</span><br></pre></td></tr></table></figure><br>这只是对第一个参数中传递的iterable元素进行求和，而将第二个元素视为总和的初始值。<code>sum</code>函数的声明为<code>sum(iterable, start=0, /)</code>，在上例中如果不传仅限位置参数<code>start</code>，将取默认值<code>0</code>，在这种情况下将抛出<code>TypeError</code>：不能将整数和列表相加。</p>
<p>毫无疑问，这种方法是所有答案中最「<strong>简洁</strong>」、最「<strong>聪明</strong>」的，答案评论区争论的焦点之一就是低效，原因是列表连接时产生了大量不必要的复制，时间复杂度高达$O(n^2)$。当然，这并非本文重点，有兴趣可移步<a target="_blank" rel="noopener" href="https://mathieularose.com/">Mathieu Larose</a>的文章：<a target="_blank" rel="noopener" href="https://mathieularose.com/how-not-to-flatten-a-list-of-lists-in-python">How Not to Flatten a List of Lists in Python</a>。</p>
<p>同时，该方法仅用于二维嵌套列表，对于更深层级的嵌套，则需寻求其他方法。</p>
<h3 id="2-5-方法五：现有的轮子"><a href="#2-5-方法五：现有的轮子" class="headerlink" title="2.5.方法五：现有的轮子"></a>2.5.方法五：现有的轮子</h3><p>有这么句话，<font color=red><b>Do not reinvent the wheel!</b></font>，即<font color=red><b>不要重复造轮子</b></font>。<a target="_blank" rel="noopener" href="https://stackoverflow.com/users/1977620/max-malysh">Max Malysh</a>可谓是贯彻了这一理念，很多第三方库甚至是python自带的库或函数，都提供了相应的方法：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">src = [[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>], [<span class="number">7</span>], [<span class="number">8</span>, <span class="number">9</span>]]</span><br><span class="line"><span class="comment"># Django</span></span><br><span class="line"><span class="keyword">from</span> django.contrib.admin.utils <span class="keyword">import</span> flatten</span><br><span class="line">dst = flatten(src)</span><br><span class="line"></span><br><span class="line"><span class="comment"># Pandas</span></span><br><span class="line"><span class="keyword">from</span> pandas.core.common <span class="keyword">import</span> flatten</span><br><span class="line">dst = <span class="built_in">list</span>(flatten(src))</span><br><span class="line"></span><br><span class="line"><span class="comment"># Numpy</span></span><br><span class="line"><span class="keyword">from</span> numpy <span class="keyword">import</span> concatenate</span><br><span class="line">dst = <span class="built_in">list</span>(concatenate(src))</span><br><span class="line"></span><br><span class="line"><span class="comment"># Matplotlib</span></span><br><span class="line"><span class="keyword">from</span> matplotlib.cbook <span class="keyword">import</span> flatten</span><br><span class="line">dst = <span class="built_in">list</span>(flatten(src))</span><br><span class="line"></span><br><span class="line"><span class="comment"># Unipath</span></span><br><span class="line"><span class="keyword">from</span> unipath.path <span class="keyword">import</span> flatten</span><br><span class="line">dst = <span class="built_in">list</span>(flatten(src))</span><br><span class="line"></span><br><span class="line"><span class="comment"># Setuptools</span></span><br><span class="line"><span class="keyword">from</span> setuptools.namespaces <span class="keyword">import</span> flatten</span><br><span class="line">dst = <span class="built_in">list</span>(flatten(src))</span><br></pre></td></tr></table></figure><br>pandas提供的<code>flatten</code>函数不仅能解决多层嵌套，还能连接整数和列表，这或许是终极答案了。</p>
<p>关于造轮子的说法，使用别人造好了的轮子固然可以提高效率，但是自己造轮子难道不是一种更好的学习方式吗？正如<a target="_blank" rel="noopener" href="https://stackoverflow.com/users/6084517/nathan-chappell">Nathan Chappell</a>所言：</p>
<blockquote>
<p>All these great libraries reinvented the wheel, why shouldn’t I?</p>
</blockquote>
<h3 id="2-6-方法六：operator"><a href="#2-6-方法六：operator" class="headerlink" title="2.6.方法六：operator"></a>2.6.方法六：<code>operator</code></h3><p><code>operator</code>模块中提供了很多方法，例如<code>concat</code>、<code>add</code>等，需要配合<code>functools.reduce</code>一起使用：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> reduce</span><br><span class="line"><span class="keyword">import</span> operator</span><br><span class="line">src = [[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>], [<span class="number">7</span>], [<span class="number">8</span>, <span class="number">9</span>]]</span><br><span class="line"></span><br><span class="line">reduce(operator.concat, src)</span><br><span class="line">reduce(operator.add, src)</span><br></pre></td></tr></table></figure></p>
<h3 id="2-6-方法七：map"><a href="#2-6-方法七：map" class="headerlink" title="2.6.方法七：map"></a>2.6.方法七：<code>map</code></h3><p><a target="_blank" rel="noopener" href="https://stackoverflow.com/users/5922329/daniel-braun">Daniel Braun</a>给出的<code>map</code>方法，个人认为不是很好（可能这也是vote数比较少的原因吧）：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">def</span> <span class="title function_">flatten</span>(<span class="params">src</span>):</span><br><span class="line">    dst = []</span><br><span class="line">    tmp = <span class="built_in">list</span>(<span class="built_in">map</span>(dst.extend, src))</span><br><span class="line">    <span class="keyword">return</span> dst</span><br><span class="line"></span><br><span class="line">flatten([[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>], [<span class="number">7</span>], [<span class="number">8</span>, <span class="number">9</span>]])</span><br></pre></td></tr></table></figure></p>
<h2 id="3-其他问题"><a href="#3-其他问题" class="headerlink" title="3.其他问题"></a>3.其他问题</h2><p>上述各种方法都有一定的局限性，最大的问题就是对于数据类型的制约以及嵌套深度的限制，<a target="_blank" rel="noopener" href="https://stackoverflow.com/users/4531270/pylang">pylang</a>给出了一种适用于数字、字符串、嵌套列表及其复合体的通用方法，该方法参考了<a target="_blank" rel="noopener" href="https://stackoverflow.com/users/680/cristian">Cristian</a>的<a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists/2158532#2158532">在Flatten an irregular list of lists的回答</a>：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> Iterable </span><br><span class="line"><span class="keyword">def</span> <span class="title function_">flatten</span>(<span class="params">items</span>):</span><br><span class="line">    <span class="keyword">for</span> x <span class="keyword">in</span> items:</span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">isinstance</span>(x, Iterable) <span class="keyword">and</span> <span class="keyword">not</span> <span class="built_in">isinstance</span>(x, (<span class="built_in">str</span>, <span class="built_in">bytes</span>)):</span><br><span class="line">            <span class="keyword">yield</span> <span class="keyword">from</span> flatten(x)</span><br><span class="line">            <span class="comment"># *注：上句可展开为</span></span><br><span class="line">            <span class="comment"># for sub_x in flatten(x):</span></span><br><span class="line">            <span class="comment">#     yield sub_x</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">yield</span> x</span><br><span class="line"></span><br><span class="line"><span class="built_in">list</span>(flatten([[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>], [<span class="number">7</span>], [<span class="number">8</span>, <span class="number">9</span>]]))   <span class="comment"># 简单情况</span></span><br><span class="line"><span class="built_in">list</span>(flatten([[<span class="number">1</span>, [<span class="number">2</span>]], (<span class="number">3</span>, <span class="number">4</span>, &#123;<span class="number">5</span>, <span class="number">6</span>&#125;, <span class="number">7</span>), <span class="number">8</span>, <span class="string">&quot;9&quot;</span>])) <span class="comment"># 复杂情况</span></span><br></pre></td></tr></table></figure></p>

      
    </div>
    <div class="article-footer">
      <blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-license">
      <strong>文章作者： </strong><a href="https://hwame.top" style="color:#E541E5;"> 鴻塵</a>
    </li>
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="https://hwame.top/20210610/flatten-a-nested-list.html" title="如何将嵌套列表展开为一维" target="_blank" rel="external" style="color:#E541E5;">https://hwame.top/20210610/flatten-a-nested-list.html</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用《<a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external" style="color:#E541E5;"><u>CC BY 4.0 CN协议</u></a>》许可协议。转载请注明出处！
    </li>
  </ul>
</blockquote>


<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://hwame.top" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://hwame.top" target="_blank"><span class="text-dark">鴻塵</span><small class="ml-1x">Pythoner, Data Analyst</small></a></h3>
        <div>个人简介：处女座不适合做码农。</div>
      </div>
    </figure>
  </div>
</div>


    </div>
  </article>
  
    
  <section id="comments">
  	
      <div id="vcomments"></div>
    
  </section>


  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="/20210618/ansi-color-in-windows-cmd.html" title="Windows命令行中正确显示颜色"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;上一篇</span></a>
    </li>
    
    
    <li class="next">
      <a href="/20210112/command-line-description.html" title="命令行帮助文档语法格式详解"><span>下一篇&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
    <li class="toggle-toc">
      <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false" title="文章目录" role="button">
        <span style="color:#C71585">[&nbsp;</span><span style="color:#C71585">文章目录</span>
        <i class="text-collapsed icon icon-anchor"></i>
        <i class="text-in icon icon-close"></i>
        <span style="color:#C71585">]</span>
      </a>
    </li>
    
  </ul>
  
  
  
  <div class="bar-right">
    
    <div class="share-component" data-sites="weibo,qq,wechat,facebook,twitter" data-mobile-sites="weibo,wechat,qq,qzone"></div>
    
  </div>
  </div>
</nav>
  


</main>

  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="https://github.com/hwame" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="https://weibo.com/hwamei" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="https://www.zhihu.com/people/hwame" target="_blank" title="Zhihu" data-toggle=tooltip data-placement=top><i class="icon icon-zhihu"></i></a></li>
        
        <li><a href="https://segmentfault.com/u/hwame" target="_blank" title="Segmentfault" data-toggle=tooltip data-placement=top><i class="icon icon-segmentfault"></i></a></li>
        
        <li><a href="https://gitee.com/hwame" target="_blank" title="Gitee" data-toggle=tooltip data-placement=top><i class="icon icon-gitee"></i></a></li>
        
        <li><a href="/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        &copy; 2025 鴻塵
        
        
        <div class="publishby" style="font-family:Courier">
            <span id="busuanzi_container_site_pv">
                <i class="icon icon-eye"></i><span id="busuanzi_value_site_pv" style="font-family:Courier"></span>&nbsp;
                <i class="icon icon-users"></i><span id="busuanzi_value_site_uv" style="font-family:Courier"></span>
            </span>
            <!--
            <br>✯<a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/" style="color:#0FFFAA">鄂ICP备2020019329号</a>
            -->
            <br><i class="icon icon-clock" style="transform:rotate(90deg)"></i><span id="sitetime" style="font-family:Courier"></span>
        </div>
        
        <!--
        <div class="publishby">
        	Theme by <a href="https://github.com/cofess" target="_blank"> cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.
        </div>
        -->
    </div>
    
</footer>
<script>
    function siteTime(){
        window.setTimeout("siteTime()", 1000);
        var seconds = 1000;
        var minutes = seconds * 60;
        var hours = minutes * 60;
        var days = hours * 24;
        var years = days * 365;
        var today = new Date();
        var todayYear = today.getFullYear();
        var todayMonth = today.getMonth()+1;
        var todayDate = today.getDate();
        var todayHour = today.getHours();
        var todayMinute = today.getMinutes();
        var todaySecond = today.getSeconds();
        /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
        year - 作为date对象的年份，为4位年份值
        month - 0-11之间的整数，做为date对象的月份
        day - 1-31之间的整数，做为date对象的天数
        hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
        minutes - 0-59之间的整数，做为date对象的分钟数
        seconds - 0-59之间的整数，做为date对象的秒数
        microseconds - 0-999之间的整数，做为date对象的毫秒数 */
        var t1 = Date.UTC(2020,05,19,21,20,52); //建站时间
        var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
        var diff = t2-t1;
        var diffYears = Math.floor(diff/years);
        var diffDays = Math.floor((diff/days)-diffYears*365);
        var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
        var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
        var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
        // 将「数字」转「补零字符串」
        var y = diffYears.toString()
        var d = diffDays.toString().padStart(3, '0')
        var h = diffHours.toString().padStart(2, '0')
        var m = diffMinutes.toString().padStart(2, '0')
        var s = diffSeconds.toString().padStart(2, '0')
        document.getElementById("sitetime").innerHTML=y+":"+d+":"+h+":"+m+":"+s;
    }
    siteTime();
</script>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<div id="go-top"></div>
<style type="text/css">
#go-top {
 width:40px;height:40px;
 background-color:#DDA0DD;
 position:relative;
 border-radius:20px;
 position:fixed;right:20px;bottom:50px;
 cursor:pointer;display:none;
}
#go-top:after {
 content:" ";
 position:absolute;left:14px;top:14px;
 border-top:2px solid #fff;border-right:2px solid #fff;
 width:12px;height:12px;
 transform:rotate(-45deg);
}
#go-top:hover {
 background-color:#8A2BE2;
}
</style>
<script>
$(function () {
  var top=$("#go-top");
  $(window).scroll(function () {
    ($(window).scrollTop() > 300) ? top.show(300) : top.hide(200);
    $("#go-top").click(function () {
      $('body,html').animate({scrollTop:0});
      return false();
    })
  });
});
</script>

<script src="/js/plugin.min.js"></script>


<script src="/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/js/insight.js"></script>





   




   
    

  <script src='/waline.js'></script>
  <link rel="stylesheet" type="text/css" href="/waline.css" />
  
  <script type="text/javascript">
 
  
Waline.init({
      el: '#vcomments',
      serverURL: 'https://waline.hwame.top',
});
  </script>

     


<!-- 20201211添加判断 -->

   
  <script src="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script>
  <script>
  //利用 FancyBox 实现点击图片放大
  $(document).ready(function() {
    $('article img').not('[hidden]').not('.panel-body img').each(function() {
      var $image = $(this);
      var imageCaption = $image.attr('alt');
      var $imageWrapLink = $image.parent('a');
      if ($imageWrapLink.length < 1) {
        var src = this.getAttribute('src');
        var idx = src.lastIndexOf('?');
        if (idx != -1) {
          src = src.substring(0, idx);
        }
        $imageWrapLink = $image.wrap('<a href="' + src + '"></a>').parent('a');
      }
      $imageWrapLink.attr('data-fancybox', 'images');
      if (imageCaption) {
        $imageWrapLink.attr('data-caption', imageCaption);
      }
    });
    $().fancybox({
      selector: '[data-fancybox="images"]',
      hash: false,
      loop: true,
    });
  });
  </script>







  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
      z-index: 2;
    }

    .highlight-wrap:hover .copy-btn,
        .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  
  <script>
    addLoadEvent(()=>{
      $('.highlight').each(function (i, e) {
        var $wrap = $('<div>').addClass('highlight-wrap')
        $(e).after($wrap)
        $wrap.append($('<button>').addClass('copy-btn').append('一键复制').on('click', function (e) {
          var code = $(this).parent().find(".code")[0].innerText
          
          var ta = document.createElement('textarea')
          document.body.appendChild(ta)
          ta.style.position = 'absolute'
          ta.style.top = '0px'
          ta.style.left = '0px'
          ta.value = code
          ta.select()
          ta.focus()
          var result = document.execCommand('copy')
          document.body.removeChild(ta)
          
            if(result)$(this).text('复制成功')
            else $(this).text('复制失败')
          
          $(this).blur()
        })).on('mouseleave', function (e) {
          var $b = $(this).find('.copy-btn')
          setTimeout(function () {
            $b.text('一键复制')
          }, 300)
        }).append(e)
      })
    })
  </script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</body>
</html>